package com.dfd.shiro.config;

import com.dfd.shiro.model.User;
import com.dfd.shiro.service.PermissionService;
import com.dfd.shiro.service.RoleService;
import com.dfd.shiro.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;


    /**
     *自定义的授权方法，当shiro触发授权认证时，会自动调用该方法从数据库中
     * 获取用户的权限信息。
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) principalCollection.getPrimaryPrincipal();
        User user = userService.findByUsername(username);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        根据用户id查询角色
        List<String> roles = roleService.selectRoleByUserId(user.getUserId());
        info.addRoles(roles);
//        根据用户名查询权限
        List<String> permissions = permissionService.selectPermissionByUserId(user.getUserId());
        info.addStringPermissions(permissions);
        System.out.println(principalCollection);
        return info;
    }

    /**
     * 自定义登录认证的方法，shiro底层会自动的调用该方法从数据库中获取
     * 要认证的数据
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取要认证的用户的身份
        String username = token.getPrincipal().toString();
        //调用业务层从数据库中获取用户的信息
        User user = userService.findByUsername(username);
        //将数据存储到info对象中返回
        if (user != null) {
            //加盐
            String salt = "bjsxt";
            //创建info对象存储数据并返回
            AuthenticationInfo info = new SimpleAuthenticationInfo(token.getPrincipal(), user.getPassword(), ByteSource.Util.bytes(salt), token.getPrincipal().toString());
            return info;
        }

        return null;
    }
}
